package com.travel.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;

import com.travel.core.DaoFactory;
import com.travel.dao.ISpotDao;

public class StatisticsDrawServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final ISpotDao SPOT_DAO = DaoFactory.getDao(ISpotDao.class);

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// added by yb增加当前城市的判断
		String currLoc = request.getParameter("loc");
		if (StringUtils.isBlank(currLoc)) {
			currLoc = "0773";// 默认显示桂林
		}
		System.out.println("获取到的参数为：" + currLoc);

		int endYear = Calendar.getInstance().get(Calendar.YEAR);
		int startYear = endYear - 2;
		List<Map<String, Object>> result = new ArrayList<>(endYear - startYear);
		List<Map<String, Object>> localeStatictics = SPOT_DAO.getStaticticsByYear(currLoc, startYear, endYear);

		if (Objects.nonNull(localeStatictics) && !localeStatictics.isEmpty()) {
			int[] startSeasons = new int[4];
			Map<String, Object> startMap = new HashMap<>(4);
			for (Map<String, Object> month : localeStatictics) {
				String[] ym = month.get("ym").toString().trim().split("-");
				if (Integer.parseInt(ym[0]) == startYear) {
					int seasonIndex = (Integer.parseInt(ym[1]) - 1) / 3;
					startSeasons[seasonIndex] += Integer.parseInt(month.get("count").toString().trim());
				}
			}
			startMap.put("year", startYear);
			startMap.put("yearValue", startSeasons);
			result.add(startMap);

			int actualEndYear = endYear - 1;
			int[] endSeasons = new int[4];
			Map<String, Object> endMap = new HashMap<>(4);
			for (Map<String, Object> month : localeStatictics) {
				String[] ym = month.get("ym").toString().trim().split("-");
				if (Integer.parseInt(ym[0]) == actualEndYear) {
					int seasonIndex = (Integer.parseInt(ym[1]) - 1) / 3;
					endSeasons[seasonIndex] += Integer.parseInt(month.get("count").toString().trim());
				}
			}
			endMap.put("year", actualEndYear);
			endMap.put("yearValue", endSeasons);
			result.add(endMap);
		}
		response.getWriter().write(new JSONArray(result).toString());
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
